package menu_api

import (
	"benkendSystem/database"
	"benkendSystem/models"
	"benkendSystem/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

// AddMenuForRole 给角色赋予菜单权限
func AddMenuForRole(c *gin.Context) {
	in := new(AddMenuForRoleRequest)
	err := c.ShouldBindJSON(in)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	//  判断是否菜单已在角色中
	var menuIds []int64
	err = database.DB.Model(new(models.RoleMenu)).Select("menu_id").Where("role_id = ?", in.RoleId).Find(&menuIds).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	var Names []string
	for _, v := range in.MenuIds {
		var name string
		if utils.Contains(menuIds, v) {
			err = database.DB.Model(new(models.Menu)).Select("name").Where("id = ?", v).Find(&name).Error
			if err != nil {
				c.JSON(http.StatusOK, gin.H{
					"code": 500,
					"msg":  "系统错误",
				})
				return
			}
			Names = append(Names, name)
			continue
		}
		err = database.DB.Model(new(models.RoleMenu)).Create(&models.RoleMenu{
			RoleId: in.RoleId,
			MenuId: v,
		}).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "操作失败",
			})
			return
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "操作成功",
		"data": gin.H{
			"success": len(in.MenuIds) - len(Names),
			"failed":  len(Names),
		},
	})

}
